#!/usr/bin/env python
# coding: utf-8
"""
    log server for vim script netlog.vim

    Copyright (C) 2011  Pan, Shi Zhu

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

import socket

DEFAULT_PORT = 10007
BUFSIZE = 1024

# sample server func
def sample_server_func(indata):
    if indata == '__close':
        return None  # to shutdown the server
    elif indata == '__disconnect':
        return 0     # to disconnect
    elif indata == '__hello':
        return "acknowledgement"
    else:
        return 0

def udpslice(sendfunc, data, addr):
    senddata = data
    while len(senddata) >= BUFSIZE:
        sendfunc(senddata[0:BUFSIZE], addr)
        senddata = senddata[BUFSIZE:]
    if senddata[-1:] == "\n":
        sendfunc(senddata, addr)
    else:
        sendfunc(senddata+"\n", addr)

def udpserver(func, port=DEFAULT_PORT):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setblocking(1)
    name = 'udp server'
    try:
        s.bind(('', port))
    except Exception, inst:
        s.close()
        print name, "start fail:", inst
        return
    print name,'on port', port
    try:
        while True:
            data, addr = s.recvfrom(BUFSIZE)
            data = data[:-1]
            print '%r: %s' % (addr[0], data)
            if func:
                try:
                    ret = func(data)
                except Exception:
                    s.sendto('\n', addr)
                    continue
                if ret == None:
                    s.sendto('server closed\n', addr)
                    break
                elif ret == 0:
                    pass
                else:
                    s.sendto('\n', addr)
            else:
                s.sendto('\n', addr)
    except KeyboardInterrupt:
        print
    s.close()
    print name,"exit" 

if __name__ == "__main__":
    udpserver(sample_server_func)
